package cn.edu.hcnu.service.impl;

import cn.edu.hcnu.domain.User;
import cn.edu.hcnu.mapper.UserMapper;
import cn.edu.hcnu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @description:
 * @author: Administrator
 * @time: 2023/6/19 18:07
 */
@Service
@CacheConfig(cacheNames = "user")
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    @Cacheable(unless = "#result==null", key = "'all'")
    public List<User> getAll() {
        return userMapper.list();
    }

    @Override
    @Cacheable(unless = "#result==null", key = "#id")
    public User getUserById(Integer id) {
        return userMapper.queryByID(id);
    }

    @Override
    @Caching(
            put = {
                    @CachePut(key = "#user.id", unless = "#result==null")
            },
            evict = {
                    @CacheEvict(key = "'all'")
            })

    public User addUser(User user) {
        userMapper.insertUser(user);
        return user;
    }

    @Override
    @Caching(
            put = {
                    @CachePut(key = "#user.id", unless = "#result==null")
            },
            evict = {
                    @CacheEvict(key = "'all'")
            })
    public User updateUser(User user) {
        userMapper.updateUser(user);
        return userMapper.queryByID(user.getId());
    }

    @Override
    @Caching(
            evict = {
                    @CacheEvict(key = "#id", condition = "#result==1"),
                    @CacheEvict(key = "'all'")
            })

    public Integer deleteUser(Integer id) {
        return userMapper.deleteUser(id);
    }

    @Override
    public List<User> findByName(String name) {
        return userMapper.queryLike(name);
    }
}
